/*
 * Copyright 2011 Subhabrata Ghosh <subho.ghosh at langene.net>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */



package net.langene.common;

//~--- non-JDK imports --------------------------------------------------------

import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;

import org.slf4j.Logger;

//~--- JDK imports ------------------------------------------------------------

import java.util.Collection;
import java.util.Iterator;

//~--- classes ----------------------------------------------------------------

/**
 * Class contains common utility methods.
 *
 * @author Subhabrata Ghosh <subho.ghosh at langene.net>
 */
public class ProgramUtils {

    /**
     * Print the program usage with options.
     *
     * @param app Program Name
     * @param message Error message.
     * @param options Options Handle.
     */
    public static void usage(String app, String message, Options options) {
        System.out.println("ERROR : " + message);
        System.out.println("Usage :\n\t" + app + " <options>");
        System.out.println("\tList of Options:");

        Collection<Option>	ops = options.getOptions();

        for (Iterator<Option> it = ops.iterator(); it.hasNext(); ) {
            Option	op = it.next();

            System.out.println("\t\t\t-" + op.getLongOpt() + "\t" + (op.isRequired()
                    ? "Required"
                    : "Optional") + "\t"
                                                                     + op.getDescription());
        }
    }

    /**
     * Print the Exception Stack Trace, including inner exceptions.
     * Will log a debug message.
     * 
     * @param logger
     * @param ex 
     */
    public static void printStacktrace(Logger logger, Throwable ex) {
        if (ex == null) {
            return;
        }

        logger.debug(ex.getLocalizedMessage());

        StackTraceElement[]	ste = ex.getStackTrace();

        if ((ste != null) && (ste.length > 0)) {
            for (int ii = 0; ii < ste.length; ii++) {
                logger.debug("from " + ste[ii].getClassName() + "." + ste[ii].getMethodName()
                             + "() [" + ste[ii].getFileName() + ":" + ste[ii].getLineNumber()
                             + "]");
            }
        }

        if (ex.getCause() != null) {
            printStacktrace(logger, ex.getCause());
        }
    }
}


//~ Formatted by Jindent --- http://www.jindent.com
